//
//  SafeBasicInformationViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/9/29.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "UIActionSheet+Common.h"
// 附件
#import "H1_ImagesCell.h"
#import "PictureViewController.h"

// 安全基本信息模型
#import "SecurityRecordBasic.h"
// 显示cell
#import "DefaineCell.h"
// 单行输入cell
#import "QianDTableCell.h"
// 多行输入cell
#import "B_wuLiaoCell.h"
// 位置cell
#import "PositionTableCell.h"
// 位置控制器
#import "OrientationViewController.h"

#import "SafeBasicInformationViewController.h"

@interface SafeBasicInformationViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

// 表格
@property (strong, nonatomic) TPKeyboardAvoidingTableView *tableView;
// 施工合同段
@property (strong, nonatomic) DefaineCell *segmentCell;
// 施工合同价
@property (strong, nonatomic) DefaineCell *priceCell;

/**保存数据模型*/
@property (strong, nonatomic) SecurityRecordBasic *saveModel;

/**安全类型*/
@property (strong, nonatomic) NSArray *safeTypeArr;

// 附件模型
@property (strong, nonatomic) Tweet *curTweet;
// 图片路径数组
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;
// 位置信息记录
@property (strong, nonatomic) PositionBlockModel *blockModel;
// 当前被点的地址数据模型
@property (strong, nonatomic) AddressModel *addressModel;
// 总监意见(是否同意)
@property (strong, nonatomic) UISwitch *networkSwitch;

//天气地区
@property (strong, nonatomic)NSMutableArray *weatherArr;

@end


@implementation SafeBasicInformationViewController


// 总监意见(是否同意)
- (UISwitch *)networkSwitch {
    if (!_networkSwitch) {
        // 滑块
        _networkSwitch = [[UISwitch alloc] init];
        _networkSwitch.onTintColor = UIColorFromRGB(0x45de89);
        _networkSwitch.on = YES;
        [_networkSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
        if (![role isEqual:@"USER_01"]) {
            _networkSwitch.enabled = NO;
            
        } else {
            self.saveModel.chiefSupervisorOpinionState = @"1";
        }
    }
    return _networkSwitch;
}

// 是否同意
- (void)switchAction:(UISwitch *)switchButton {
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        NSLog(@"同意");
        self.saveModel.chiefSupervisorOpinionState = @"1";
        
    } else {
        NSLog(@"不同意");
        self.saveModel.chiefSupervisorOpinionState = @"0";
    }
}


- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

// 安全类型
- (NSArray *)safeTypeArr {
    if (!_safeTypeArr) {
        _safeTypeArr = @[@"施工三类人员核查", @"特种作业人员持证情况", @"监理安全巡查", @"危险性较大工程监理检查", @"施工设备进场验收监理核查"];
    }
    return _safeTypeArr;
}

// 保存数据模型
- (SecurityRecordBasic *)saveModel {
    if (!_saveModel) {
        _saveModel = [[SecurityRecordBasic alloc] init];
    }
    return _saveModel;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 188) style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColorFromRGB(0xf2f2f2);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorColor = UIColorFromRGB(0xeeeeee);
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
        
        [_tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"bCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defineCell"];
        [_tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"positionCell"];
        [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //天气地区数组
    self.weatherArr = [LSUtility getWeatherArea];
    
    [self setData];
    
    //附件模型
    _curTweet = [[Tweet alloc] init];
    [self.view addSubview:self.tableView];
    
    // 附件通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_safe" object:nil];
}
-(void)setData{
    //天气数组
    NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
    self.saveModel.areaStr=[self.weatherArr firstObject];
    self.saveModel.weather=[[wArr firstObject]objectForKey:self.saveModel.areaStr];
}
- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

- (void)viewWillAppear:(BOOL)animated {
    // 暂存/提交
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotificationAction:) name:@"saveSafeBase" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"saveSafeBase" object:nil];
}

#pragma mark - 暂存/保存 安全基本信息
- (void)getNotificationAction:(NSNotification *)notification {
    // 接收通知来的信息
    NSDictionary *typeDic = [notification object];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 安全施工三类人员
    if ([typeDic[@"safeType"] isEqualToString:@"1"]) {
        /**安全类型*/
        self.saveModel.recordType = @"SAFE_RECORD_02";
        
        // 特种作业人员持证情况
    } else if ([typeDic[@"safeType"] isEqualToString:@"2"]) {
        /**安全类型*/
        self.saveModel.recordType = @"SAFE_RECORD_04";
        
        // 监理安全巡查
    } else if ([typeDic[@"safeType"] isEqualToString:@"3"]) {
        /**安全类型*/
        self.saveModel.recordType = @"SAFE_RECORD_01";
        
        // 危险性较大工程监理检查
    } else if ([typeDic[@"safeType"] isEqualToString:@"4"]) {
        /**安全类型*/
        self.saveModel.recordType = @"SAFE_RECORD_03";
        
        // 施工设备进场验收监理核查
    } else if ([typeDic[@"safeType"] isEqualToString:@"5"]) {
        /**安全类型*/
        self.saveModel.recordType = @"SAFE_RECORD_05";
    }
    /**标题*/
    NSInteger index = [typeDic[@"safeType"] integerValue] - 1;
    if (self.saveModel.recordNumber) {
        self.saveModel.recordTitle = [NSString stringWithFormat:@"%@_%@", self.safeTypeArr[index], self.saveModel.recordNumber];
        
    } else {
        self.saveModel.recordTitle = [NSString stringWithFormat:@"%@_", self.safeTypeArr[index]];
    }
    // UUID
    NSString *UUIDStr = [NSUUID UUID].UUIDString;
    // 状态
    NSString *recifyState;
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]) {
        recifyState = @"0";
        
    } else if ([role isEqualToString:@"USER_01"]) {
        recifyState = @"1";
    }
    
    if(!self.saveModel.constructProUnitName||self.saveModel.constructProUnitName.length==0){
        [LSUtility showToastWithMessage:@"请选择施工单位" inView:kKeyWindow Andtime:1.];
        return;
    }
    if(!self.saveModel.addInfo||self.saveModel.addInfo.length==0){
        [LSUtility showToastWithMessage:@"位置信息不能为空" inView:kKeyWindow Andtime:1.];
        return;
    }
    // 位置ID
    self.saveModel.addId = self.blockModel.aID;
    /*
     *  记录表新增数据
     */
    NSString *weather=[NSString stringWithFormat:@"%@/%@",DEFISNUL(self.saveModel.areaStr),DEFISNUL(self.saveModel.weather)];
    
    // 字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":DEFISNUL(UUIDStr),
                   @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                   @"SUPERVISOR_PRO_UNIT_ID":DEFISNUL(self.saveModel.supervisorProUnitId),
                   @"CONSTRUCT_PRO_UNIT_ID":DEFISNUL(self.saveModel.constructProUnitId),
                   @"SUPERVISOR_PRO_UNIT_NAME":DEFISNUL(self.saveModel.supervisorProUnitName),
                   @"CONSTRUCT_PRO_UNIT_NAME":DEFISNUL(self.saveModel.constructProUnitName),
                   @"SUPERVISOR_CONTRACT_NUMBER":DEFISNUL(self.saveModel.supervisorContractNumber),
                   @"CONSTRUCT_CONTRACT_NUMBER":DEFISNUL(self.saveModel.constructContractNumber),
                   @"RECORD_USER":DEFISNUL(DEF_PERSISTENT_GET_OBJECT(@"userid")),
                   @"RECORD_TYPE":DEFISNUL(self.saveModel.recordType),
                   @"RECORD_TITLE":DEFISNUL(self.saveModel.recordTitle),
                   @"RECORD_CONTENT":DEFISNUL(self.saveModel.recordContent),
                   @"STATE":DEFISNUL(typeDic[@"saveType"]),
                   @"RECORD_NUMBER":DEFISNUL(self.saveModel.recordNumber),
                   @"SUPERVISOR_OPINION":DEFISNUL(self.saveModel.supervisorOpinion),
                   @"CHIEF_SUPERVISOR_OPINION":DEFISNUL(self.saveModel.chiefSupervisorOpinion),
                   @"CHIEF_SUPERVISOR_OPINION_STATE":DEFISNUL(self.saveModel.chiefSupervisorOpinionState),
                   @"PROJECT_CONTENT":DEFISNUL(self.saveModel.projectContent),
                   @"OTHER_INFO":DEFISNUL(self.saveModel.otherInfo),
                   @"PROBLEM_AND_DEAL":DEFISNUL(self.saveModel.problemAndDeal),
                   @"WEATHER":weather,
                   @"ADD_ID":DEFISNUL(self.saveModel.addId),
                   @"ADD_INFO":DEFISNUL(self.saveModel.addInfo),
                   @"CONSTRUCT_CONTRACT_MONEY":DEFISNUL(self.saveModel.constructContractMoney),
                   @"RECIFY_STATE":DEFISNUL(recifyState),
                   @"EXTEND_INFO":@"",
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                   @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                   @"CREATE_IP":DEFISNUL([LSUtility getIPAddress]),
                   @"MODIFY_USER_NAME":@"",
                   @"MODIFY_TIME":@"",
                   @"MODIFY_IP":@"",
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAFE_RECORD_BASIC];
    if (isAdd) {
        NSLog(@"添加安全基本信息成功");
        
    } else {
        NSLog(@"添加安全基本信息失败");
    }
    
    [self insertAttachment:UUIDStr];
    
    
}

#pragma mark - 先新增附件表
- (void)insertAttachment:(NSString *)fileID {
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    for (NSString *imageUrlStr in self.selectedAssetURLs) {
        // 图片
        UIImage *image = [UIImage imageWithContentsOfFile:imageUrlStr];
        
        // filePath
        NSArray *arr = [imageUrlStr componentsSeparatedByString:@"/"];
        NSString *imageName = [arr lastObject];
        NSDate *senddate = [NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyyMMdd"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        //拼接路径
        NSString *filePath = [NSString stringWithFormat:@"/%@/%@.png", locationString, imageName];
        
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"ID":DEFISNUL([NSUUID UUID].UUIDString),
                       //文件所属记录类型
                       @"FILE_TYPE_ID":DEFISNUL(self.saveModel.recordType),
                       //文件所属记录
                       @"FILE_ID":fileID,
                       //所属项目
                       @"PRO_ID":PROID,
                       //文件名称
                       @"FILE_NAME":imageName,
                       //文件大小
                       @"FILE_SIZE":[LSUtility imageDataLenth:image],
                       //文件后缀名
                       @"FILE_SUFFIX":@".png",
                       //文件路径
                       @"FILE_PATH":filePath,
                       @"FILE_DESC":@"",
                       //附件状态
                       @"FILE_STATE":@"0",
                       //扩展信息
                       @"EXTEND_INFO":@"",
                       //创建人
                       @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                       //创建时间
                       @"CREATE_TIME":[LSUtility dateNow],
                       //创建IP
                       @"CREATE_IP":[LSUtility getIPAddress],
                       @"MODIFY_USER_NAME":@"",
                       @"MODIFY_IP":@"",
                       @"MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"ADD"
                       };
        
        BOOL isAdd = [dbhelper DataBase:db insertReplaceKeyValues:pragameDic intoTable:ATTACHMENT];
        
        if (isAdd) {
            NSLog(@"添加安全附件成功");
            
        } else {
            NSLog(@"添加安全附件失败");
        }
    }
    // 传参
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    // 基本信息ID
    [parameDic setObject:fileID forKey:@"safeBaseID"];
    // 标题
    if (self.saveModel.recordTitle) {
        [parameDic setObject:self.saveModel.recordTitle forKey:@"title"];
    }
    // 编号
    if (self.saveModel.recordNumber) {
        [parameDic setObject:self.saveModel.recordNumber forKey:@"recordNumber"];
    }
    // 通知(暂存/保存检查信息)
    [[NSNotificationCenter defaultCenter] postNotificationName:@"saveSafeCheck" object:parameDic];
}

#pragma MARK - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 12;
        
    } else if (section == 1) {
        if([self.typeStr isEqualToString:@"4"]){
            return 5;
        }else{
            return 4;
        }
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 44;
        
    } else if (indexPath.section == 1) {
        //        if (self.isDevice && indexPath.row == 3) {
        //            return 0.01;
        //
        //        } else if (!self.isDanger && indexPath.row == 4) {
        //            return 0.01;
        //        }
        return 120;
        
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"添加照片"];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 0) {
        // 项目名称
        if (row == 0) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"项目名称";
            defineCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
            return defineCell;
            
            // 监理单位
        } else if (row == 1) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"监理单位";
            
            // 查找监理单位
            NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
            FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
            [db open];
            FMResultSet *result = [db executeQuery:sqlStr];
            while ([result next]) {
                // 单位名称
                NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
                self.saveModel.supervisorProUnitName = proName;
                // 单位ID
                self.saveModel.supervisorProUnitId = [result stringForColumn:@"ID"];
                defineCell.text.text = proName;
            }
            [db close];
            return defineCell;
            
            // 施工单位
        } else if (row == 2) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            defineCell.title.text = @"施工单位";
            defineCell.text.text = self.saveModel.constructProUnitName ? self.saveModel.constructProUnitName : @"请选择施工单位";
            return defineCell;
            
            // 编号
        } else if (row == 3) {
            QianDTableCell *qianCell = [tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            qianCell.title.text = @"编号            ";
            qianCell.textField.placeholder = @"请输入记录编号";
            qianCell.textValueChangedBlock = ^(NSString *str) {
                self.saveModel.recordNumber = str;
            };
            return qianCell;
            
            // 监理合同段
        } else if (row == 4) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"监理合同段";
            // 查找监理合同段
            NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_00'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
            FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
            [db open];
            FMResultSet *result = [db executeQuery:sqlStr];
            while ([result next]) {
                NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
                defineCell.text.text = contrctNumber;
                // 记录监理合同段
                self.saveModel.supervisorContractNumber = contrctNumber;
            }
            [db close];
            return defineCell;
            
            // 施工合同段
        } else if (row == 5) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            self.segmentCell = defineCell;
            defineCell.title.text = @"施工合同段";
            return defineCell;
            
            // 施工合同价(万元)
        } else if (row == 6) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            self.priceCell = defineCell;
            defineCell.title.text = @"施工合同价(万元)";
            return defineCell;
            
            // 所在区域
        } else if (row == 7) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            defineCell.title.text = @"所在区域";
            defineCell.text.text = self.saveModel.areaStr ? self.saveModel.areaStr : @"请选择所在区域";
            return defineCell;
            
            // 天气
        } else if (row == 8) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"天气";
            defineCell.text.text = self.saveModel.weather;
            return defineCell;
            
            // 工程地点
        } else if (row == 9) {
            PositionTableCell *positionCell =[tableView dequeueReusableCellWithIdentifier:@"positionCell" forIndexPath:indexPath];
            positionCell.isEdit = YES;
            positionCell.title.text = @"工程地点";
            if (self.saveModel.addInfo.length>0) {
                NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.saveModel.addInfo];
                positionCell.btnStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"leftDistanceStr"]];
                
            } else {
                positionCell.btnStr = @"请选择工程地点";
            }
            
            // 位置cell的Block
            positionCell.cliclWzBlock = ^{
                OrientationViewController *location=[[OrientationViewController alloc]init];
                location.flagStr = @"jilu";
                location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr3];
                location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr4];
                location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                
                location.addressModel = self.addressModel;
                location.aID = self.blockModel.aID;
                location.firstID = self.blockModel.firstID;
                location.secondID = self.blockModel.secondID;
                location.thirdID = self.blockModel.thirdID;
                location.keyStr = self.blockModel.keyStr;
                location.number = self.blockModel.number;
                location.position = self.blockModel.position;
                location.selectedX = self.blockModel.selectedX;
                location.selectedY = self.blockModel.selectedY;
                location.scale = self.blockModel.scale;
                
                if (location.number) {
                    location.hC = YES;
                }
                [self.navigationController pushViewController:location animated:YES];
                
                // 回传位置值
                location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                    self.blockModel = model;
                    self.addressModel = addModel;
                    self.saveModel.addInfo = addInfoStr;
                    
                    // 刷新位置值
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:9 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                };
            };
            return positionCell;
            
            // 核查日期
        } else if (row == 10) {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"核查日期";
            
            // 获取当下日期
            NSDate *currentDate = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            NSString *dateStr = [formatter stringFromDate:currentDate];
            defineCell.text.text = dateStr;
            return defineCell;
            
            // 核查人员
        } else {
            DefaineCell *defineCell = [tableView dequeueReusableCellWithIdentifier:@"defineCell" forIndexPath:indexPath];
            defineCell.title.text = @"核查人员";
            defineCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"realname");
            return defineCell;
        }
    } else if (section == 1) {
        B_wuLiaoCell *bCell = [tableView dequeueReusableCellWithIdentifier:@"bCell" forIndexPath:indexPath];
        if(![self.typeStr isEqualToString:@"4"]){
            row = row +1;
        }
        // 工程内容
        if (row == 0) {
            bCell.title.text = @"工程内容:";
            bCell.text.placeholder = @"请输入工程内容";
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.saveModel.projectContent = valueStr;
            };
            
            // 其他有关情况
        } else if (row == 1) {
            bCell.title.text = @"其他有关情况:";
            bCell.text.placeholder = @"请输入其他有关情况";
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.saveModel.otherInfo = valueStr;
            };
            
            // 监理审查意见
        } else if (row == 2) {
            bCell.title.text = @"监理审查意见:";
            bCell.text.placeholder = @"请输入监理审查意见";
            
            NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
            if ([role isEqual:@"USER_03"]||[role isEqual:@"USER_07"]) {
                bCell.isEdit = YES;
            }else{
                bCell.isEdit = NO;
            }
            
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.saveModel.supervisorOpinion = valueStr;
            };
            
            // 总监审查意见(是否同意)
        } else if (row == 3) {
            bCell.title.text=@"总监审查意见(是否同意):";
            bCell.text.placeholder = @"请输入总监审查意见";
            
            NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
            if (![role isEqual:@"USER_01"]) {
                bCell.isEdit = NO;
                
            }
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.saveModel.chiefSupervisorOpinion = valueStr;
            };
            
            // 添加滑块
            [bCell.contentView addSubview:self.networkSwitch];
            [self.networkSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-15);
                make.top.offset(5);
            }];
            
        } else if (row == 4) {
            bCell.title.text = @"主要问题及处理意见:";
            bCell.text.placeholder = @"请输入主要问题及处理意见";
            bCell.textValueChangedBlock = ^(NSString *valueStr){
                self.saveModel.problemAndDeal = valueStr;
            };
        }
        return bCell;
        
    } else {
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.isEdit = YES;
        [cell setTitle:@"添加照片"];
        //      [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        return cell;
    }
}


#pragma MARK - didSelectRowAtIndexPath(选择信息)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (section == 0) {
        // 选择施工单位
        if (row == 2) {
            // 查找施工单位列表
            NSArray *constructionUnitArr = [self getConstructionUnitList];
            if (constructionUnitArr.count > 0) {
                NSMutableArray *arr = [NSMutableArray array];
                NSNumber *ninit = [NSNumber numberWithInteger:0];
                for (NSDictionary *dic in constructionUnitArr) {
                    [arr addObject:dic[@"NAME"]];
                }
                [ActionSheetStringPicker showPickerWithTitle:nil rows:@[arr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
                    
                    // 修改数据
                    DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.text.text = [selectedValue firstObject];
                    NSInteger index = [[selectedIndex firstObject] integerValue];
                    NSDictionary *constructionUnitDic = constructionUnitArr[index];
                    [self checkConstruction:constructionUnitDic[@"ID"]];
                    // 暂存施工单位ID
                    DEF_PERSISTENT_SET_OBJECT(constructionUnitDic[@"ID"], @"constructionUnitID");
                    
                    // 要保存的施工单位信息
                    self.saveModel.constructProUnitId = constructionUnitDic[@"ID"];
                    self.saveModel.constructProUnitName = constructionUnitDic[@"NAME"];
                    // 刷新检查信息
                    if (self.saveModel.constructProUnitId && ![self.saveModel.constructProUnitId isEqualToString:@""]) {
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCheckInformation" object:constructionUnitDic[@"ID"]];
                        
                    }
                } cancelBlock:nil origin:self.view];
                
            } else {
                [LSUtility showToastWithMessage:@"数据为空" inView:self.view Andtime:1.0];
            }
            
            // 选择地区
        } else if (row == 7) {
            NSNumber *ninit = [NSNumber numberWithInteger:0];
            
            NSMutableArray *wArr=DEF_PERSISTENT_GET_OBJECT(@"WEATHER");
            if(!wArr){
                wArr=[NSMutableArray arrayWithObject:@{@"无":@"暂时无法获得天气信息"}];
            }
            if(self.weatherArr.count<1){
                [self.weatherArr addObject:@"无"];
            }
            [ActionSheetStringPicker showPickerWithTitle:nil rows:@[self.weatherArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                int iv = [(NSNumber*)[selectedIndex firstObject] intValue];
                NSDictionary *weadic=wArr[iv];
                NSString *address =self.weatherArr[iv];
                self.saveModel.areaStr=address;
                self.saveModel.weather=weadic[address];
                //刷新城市、刷新天气
                NSIndexPath *windexPath=[NSIndexPath indexPathForRow:8 inSection:0];
                [self.tableView reloadRowsAtIndexPaths:@[indexPath,windexPath] withRowAnimation:UITableViewRowAnimationNone];
                
            } cancelBlock:nil origin:self.view];
            
        }
        
    }
}

// 查找施工单位列表
- (NSArray *)getConstructionUnitList {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT ID, PRO_UNIT_NAME FROM PROJECT_UNIT WHERE PRO_ID = '%@' AND PRO_UNIT_TYPE = 'UNIT_02'", DEF_PERSISTENT_GET_OBJECT(@"proid")];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableArray *constructionUnitArr = [NSMutableArray array];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
        NSString *idStr = [result stringForColumn:@"ID"];
        NSString *proName = [result stringForColumn:@"PRO_UNIT_NAME"];
        [mDic setObject:idStr forKey:@"ID"];
        [mDic setObject:proName forKey:@"NAME"];
        [constructionUnitArr addObject:mDic];
    }
    [db close];
    return constructionUnitArr;
}

// 查找施工合同段及合同金额
- (void)checkConstruction:(NSString *)idStr {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT CONTRCT_NUMBER, CONTRCT_MONEY FROM PROJECT_UNIT WHERE ID = '%@'", idStr];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSString *contrctNumber = [result stringForColumn:@"CONTRCT_NUMBER"];
        NSString *contrctMoney = [result stringForColumn:@"CONTRCT_MONEY"];
        self.segmentCell.text.text = contrctNumber;
        self.priceCell.text.text = [NSString stringWithFormat:@"%.2lf", [contrctMoney doubleValue]];
        // 保存信息
        self.saveModel.constructContractNumber = contrctNumber;
        self.saveModel.constructContractMoney = contrctMoney;
    }
    [db close];
}

#pragma mark UIActionSheet M
- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

